package com.alfayun.fiscalriskanalysis.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alfayun.fiscalriskanalysis.common.HttpBadRequestException;
import com.alfayun.fiscalriskanalysis.common.HttpNotFoundException;
import com.fasterxml.jackson.annotation.JsonView;

@Controller
@RequestMapping("/admin/user")
public final class UserManageController {

	@Autowired
	private UserService userService;
	
	@GetMapping("/admins")
	public String users() {
		return "admin/admins";
	}
	
	@ResponseBody
	@GetMapping("/admins/data")
	public Map<String, List<UserVo>> listData() {
		Map<String, List<UserVo>> map = new HashMap<>();
		map.put("data", userService.list());
		return map;
	}

	@ResponseBody
	@GetMapping("/queryById/{id}")
	@JsonView(UserVo.Output.class)
	public UserVo queryById(@PathVariable int id) throws HttpNotFoundException {
		try {
			return userService.queryById(id);
		} catch (NoSuchUserException e) {
			throw HttpNotFoundException.build(e);
		}
	}

	@ResponseBody
	@PostMapping("/add")
	public User create(@RequestBody User user) throws HttpBadRequestException {
		return userService.createAdminUser(user);
	}

	@ResponseBody
	@DeleteMapping("/delete/{id}")
	public int delete(@PathVariable int id) {
		return userService.delete(id);
	}

	@ResponseBody
	@PutMapping("/update/{id}")
	public UserVo modify(@PathVariable int id, @RequestBody UserVo user)
			throws HttpNotFoundException, HttpBadRequestException {
		if (id == user.id) {
			try {
				return userService.modify(user);
			} catch (NoSuchUserException e) {
				throw HttpNotFoundException.build(e);
			}
		}

		throw HttpBadRequestException.build(
				String.format("The id in the path(%d) and body(%d) does not match.", id, user.id));
	}

}
